@Input 基礎使用
https://ithelp.ithome.com.tw/articles/10206340
@Output 基礎使用
https://ithelp.ithome.com.tw/articles/10206603
<div class="form-check">
<input class="form-check-input" type="radio" name="food" id="app" value="apple" checked [(ngModel)]="food">
<label class="form-check-label" for="app">
蘋果
</label>
</div>
<div class="form-check">
<input class="form-check-input" type="radio" name="food" id="banana" value="banana" [(ngModel)]="food">
<label class="form-check-label" for="banana">
香蕉
</label>
</div>
<div class="form-check">
<input class="form-check-input" type="radio" name="food" id="orange" value="orange" [(ngModel)]="food">
<label class="form-check-label" for="orange">
橘子
</label>
</div>
<app-menu [food]="food"></app-menu>
food = ['飯', 'oreo', '蛋糕'];
<ng-container *ngFor="let food of foods">
<p>{{food.name}} - {{food.price}}元</p>
</ng-container>
import { Component, OnInit, Input, OnChanges, SimpleChanges, SimpleChange } from '@angular/core';
@Component({
selector: 'app-menu',
templateUrl: './menu.component.html',
styleUrls: ['./menu.component.scss']
})
export class MenuComponent implements OnInit, OnChanges {
@Input() food; // 傳進來的參數
foods = []; // 顯示用
ngOnInit(): void {
}
// 原本是傳 陣列,後面 radio button 只有 string
// previousValue: any - 上次的值 (第一次會是 undefined)
// currentValue: any - 現在的值
// firstChange: boolean - 是不是第一次
ngOnChanges(changes: SimpleChanges): void {
const current = (changes.food as SimpleChange).currentValue;
const isArray = Array.isArray(current);
const beArray = isArray ? current : [current];
this.foods = beArray.map(f => {
return {name: f, price: 20};
});
}
}
angular 官網 - OnChanges
https://angular.io/api/core/OnChanges